package com.winit.openapi.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.util.RequestUtil;
import com.winit.ums.spi.commnad.CodeCommand;
import com.winit.ums.spi.supplier.SupplierService;
import com.winit.ums.spi.vo.SupplierClassVo;

/**
 * 安全拦截器
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * kang.wang    1.0           2014-10-24     Created
 * 
 * </pre>
 * @since 1.
 */
public class SecurityInterceptor implements HandlerInterceptor {

    private static final Logger logger                  = LoggerFactory.getLogger(SecurityInterceptor.class);

    /**
     * 软件供应商分组CODE
     */
    private static final String API_SOFTWARE_GROUP_CODE = "SOFTWARE";

    @Resource
    private SupplierService     umsSupplierService;

    /**
     * 现阶段需要校验平台传值的接口，主要的下单接口
     */
    private static List<String> checkList               = new ArrayList<String>();

    static {

        /**
         * ISP 下单接口
         */
        checkList.add("isp.order.createOrder");
        // checkList.add("isp.order.create");

        /**
         * ISP打印面单
         */
        checkList.add("winitLable.query");

        /**
         * 海外仓 下单接口 //
         */
        // checkList.add("wh.outbound.createOrder");
        // checkList.add("wh.outbound.createSubmittedOrder");
        // checkList.add("wh.outbound.submitOrder");

        /**
         * 分销下单
         */
        // checkList.add("wh.outbound.createDistributionOrder");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj,
                                Exception exception) throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj,
                           ModelAndView modelandview) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);

        String action = requestMsg.getAction();
        // 不在校验名单里面的直接返回
        if (!checkList.contains(action)) {
            return true;
        }

        if (!checkPlatform(requestMsg)) {
            logger.warn("无效的platform值：" + requestMsg.getPlatform() + " user: " + requestMsg.getApp_key() + " action: "
                         + requestMsg.getAction());
            throw new ApiException(ErrorCode.API_PLATFORM_CHECK_ERROR,
                requestMsg.getPlatform() == null ? "" : requestMsg.getPlatform());
        }

        return true;
    }

    private boolean checkPlatform(RequestMsg requestMsg) {

        if (null == requestMsg) {
            return false;
        }
        String platform = requestMsg.getPlatform();
        if (StringUtils.isBlank(platform)) {
            logger.error("platform值未指定，user: " + requestMsg.getApp_key() + " action: " + requestMsg.getAction());
            return true;
        }
        CodeCommand command = new CodeCommand();
        command.setCode(API_SOFTWARE_GROUP_CODE);
        List<SupplierClassVo> supplierList = new ArrayList<SupplierClassVo>();
        try {
            supplierList = umsSupplierService.querySuppliersByGroupCode(command);
        } catch (Exception e) {
            logger.error("获取platform配置信息失败.");
        }
        if (CollectionUtils.isEmpty(supplierList)) {

            return true;
        }

        for (SupplierClassVo supplierClassVo : supplierList) {
            // 校验平台值，默认不区分大小写
            if (platform.equalsIgnoreCase(supplierClassVo.getSupplierCode())) {
                return true;
            }
        }
        return false;

    }

}
